<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Tymon\JWTAuth\Contracts\JWTSubject;
use Illuminate\Support\Facades\Hash;
use App\Api\Traits\FormatBaseDate;

class AdminUser extends Authenticatable implements JWTSubject
{
    use HasFactory,FormatBaseDate;

    // 定义后台管理员状态
    const STATUS_MAP = [
        '10' => '启用',
        '20' => '禁用',
    ];

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'username',
        'password',
        'name',
        'status',
    ];

    /**
     * Get the identifier that will be stored in the subject claim of the JWT.
     *
     * @return mixed
     */
    public function getJWTIdentifier()
    {
        return $this->getKey();
    }

    /**
     * Return a key value array, containing any custom claims to be added to the JWT.
     *
     * @return array
     */
    public function getJWTCustomClaims()
    {
        return [];
    }

    /**
     * 加密用户名密码
     *
     * @param string $value
     * @return void
     */
    public function setPasswordAttribute($value)
    {
        $this->attributes['password'] = Hash::make($value);
    }

    /**
     * 用户拥有的角色 [定义正向多对多关联]
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function roles()
    {
        return $this->belongsToMany(AdminRole::class, 'admin_role_user', 'user_id', 'role_id');
    }
public function roleArr()
{
    return [2,4,5];
}
    /** 给用户新增角色
     * @param array $roleArray
     * @param object $user
     * @return mixed
     */
    public function addRoles(array $roleArray = [],object $user)
    {
        // 移除用户的所有角色...
        $user->roles()->detach();

        // 新增用户角色
        $roels = [];
        foreach ($roleArray as $roleId) {
            $roels[$roleId] = [
                'created_at' => date('Y-m-d H:i:s'),
                'updated_at' => date('Y-m-d H:i:s'),
            ];
        }
        return $user->roles()->sync($roels);
    }

}
